<template>
	<view class="container">
		<custom-status-bar></custom-status-bar>
		<!-- <uv-loading-page :loading="loading" loading-text="加载中..." font-size="24rpx"></uv-loading-page> -->
		<!-- 顶部导航 -->
		<view class="header">
			<view class="back-icon" @click="goBack">
				<uni-icons type="left" size="20" color="#1890ff"></uni-icons>
				<text>返回</text>
			</view>
			<text class="title">商品详情</text>
		</view>
		<!-- 商品主图 -->
		<image src="/static/passion-fruit-tea.jpg" class="product-image" />
		<!-- 商品信息 -->
		<view class="product-info">
			<view class="product-name">{{ product.name }}</view>
			<view class="product-english">{{ product.enname }}</view>
			<view class="product-price">¥{{ product.price }}</view>
		</view>
		<!-- 牛奶选项   数组 -->
		<view class="option-group" v-if="product.milk && product.milk.length > 0">
			<text class="option-label">{{ product.milk_desc }}</text>
			<view class="option-buttons">
				<uv-button :text="item.value" :custom-style="item.selected ? selectedStyle : unSelectedStyle"
					:color="item.selected ? selectedColor : unSelectedColor" @click="selectOption('milk', item)"
					v-for="(item, index) in product.milk" :key="index"></uv-button>
			</view>
		</view>
		<!-- 奶油选项 -->
		<view class="option-group" v-if="product.cream && product.cream.length > 0">
			<text class="option-label">{{ product.cream_desc }}</text>
			<view class="option-buttons">
				<uv-button :text="item.value" :custom-style="item.selected ? selectedStyle : unSelectedStyle"
					:color="item.selected ? selectedColor : unSelectedColor" @click="selectOption('cream', item)"
					v-for="(item, index) in product.cream" :key="index"></uv-button>
			</view>
		</view>
		<!-- 温度选项 -->
		<view class="option-group" v-if="product.tem && product.tem.length > 0">
			<text class="option-label">{{ product.tem_desc }}</text>
			<view class="option-buttons">
				<uv-button :text="item.value" :custom-style="item.selected ? selectedStyle : unSelectedStyle"
					:color="item.selected ? selectedColor : unSelectedColor" @click="selectOption('tem', item)"
					v-for="(item, index) in product.tem" :key="index"></uv-button>
			</view>
		</view>
		<!-- 糖分选项 -->
		<view class="option-group" v-if="product.sugar && product.sugar.length > 0">
			<text class="option-label">{{ product.sugar_desc }}</text>
			<view class="option-buttons">
				<uv-button :text="item.value" :custom-style="item.selected ? selectedStyle : unSelectedStyle"
					:color="item.selected ? selectedColor : unSelectedColor" @click="selectOption('sugar', item)"
					v-for="(item, index) in product.sugar" :key="index"></uv-button>
			</view>
		</view>
		<!-- 数量选择 -->
		<view class="quantity-control">
			<text class="option-label">选择数量</text>
			<uv-number-box v-model="count" @change="changeCount" :min="0" :disableMinus="count <= 0">
				<template #minus>
					<view class="minus" :class="{ 'disabled': count <= 0 }">
						<uv-icon name="minus" size="12" :color="count <= 0 ? '#ccc' : '#000'">
						</uv-icon>
					</view>
				</template>
				<template #input>
					<text style="width: 50px;text-align: center;" class="input">
						{{ count }}
					</text>
				</template>
				<template #plus>
					<view class="plus">
						<uv-icon name="plus" color="#FFFFFF" size="12">
						</uv-icon>
					</view>
				</template>
			</uv-number-box>
		</view>
		<!-- 商品描述 -->
		<view class="description">
			<view class="desc-title">商品描述</view>
			<view class="desc-content">
				{{ product.desc }}
			</view>
		</view>
		<!-- 底部操作栏 -->
		<view class="action-bar">
			<uni-goods-nav :fill="true" :options="options" :buttonGroup="buttonGroup" @click="onClick"
				@buttonClick="addCart" />
		</view>
	</view>
</template>
<script setup>
	import CustomStatusBar from '../../components/common/CustomStatusBar.vue';
	import {
		ref,
		reactive,
	} from 'vue';
	import {
		getProductDetail,
		getCollectStatus,
		addCollect,
		removeCollect,
		addShopcart,
		getShopcartCount
	} from "@/api/index.js"
	import {
		onLoad
	} from "@dcloudio/uni-app"
	const product = reactive({
		pid: '',
		desc: '',
		enname: '',
		large_img: '',
		small_img: '',
		name: '',
		price: '',
		cream: '',
		cream_desc: '',
		milk: '',
		milk_desc: '',
		sugar: '',
		sugar_desc: '',
		tem: '',
		tem_desc: '',
		count: 1
	})
	// 购物车商品总数
	const total = ref(0)
	const count = ref(1) // 计数器
	// const cart = ref(uni.getStorageSync('cart') || []);
	const sid = ref('') // 购物车标识
	let currentProduct = null
	const selectedStyle = reactive({
		borderRadius: '60rpx', //圆角
		width: '150rpx',
		height: '60rpx',
	})
	const unSelectedStyle = reactive({
		borderRadius: '60rpx', //圆角
		width: '150rpx',
		height: '60rpx',
		color: '#000'
	})
	const customTextStyle = reactive({
		color: '#8d8480'
	})
	const selectedColor = ref('#232773')
	const unSelectedColor = ref('#e8e8e8')
	const disableMinus = ref(false)
	const options = ref([{
		icon: 'cart', // cart-filled
		text: '购物车',
		info: 0
	}, {
		icon: 'heart', // heart-filled
		text: '收藏',
	}])
	const isFavorite = ref(false) // 是否收藏
	const buttonGroup = ref([{
		text: '加入购物车',
		backgroundColor: '#232773',
		color: '#fff'
	}])
	onLoad(async (query) => {
		// 获取当前购物车商品数量并更新显示
		await updateTotal()
		
		  // 确保即使 updateTotal 失败，options 中的 info 值也是有效数字
		    if (options.value[0].info === undefined || options.value[0].info === null) {
		        options.value[0].info = 0
		    }

		// 加载商品信息
		product.pid = query.pid
		//产品数据
		// loading.value = true
		const res = await getProductDetail(product.pid)
		console.log("初始化产品：", res.result[0]);
		if (res.code === 600) {
			product.cream_desc = res.result[0].cream_desc
			product.cream = formatOptions(res.result[0].cream);
			product.milk_desc = res.result[0].milk_desc
			product.milk = formatOptions(res.result[0].milk);
			product.sugar_desc = res.result[0].sugar_desc
			product.sugar = formatOptions(res.result[0].sugar);
			product.tem_desc = res.result[0].tem_desc
			product.tem = formatOptions(res.result[0].tem);
			product.name = res.result[0].name
			product.enname = res.result[0].enname
			product.price = res.result[0].price
			product.desc = res.result[0].desc
			product.large_img = res.result[0].large_img
			product.small_img = res.result[0].small_img
		}
		//查询商品收藏状态
		collectStatus();
		// console.log('onload 当前产品配置:',product)
		currentProduct = product
		console.log('当前产品配置:', currentProduct)
	})
	const selectOption = (type, item) => {
		const keys = {
			tem: product.tem,
			sugar: product.sugar,
			cream: product.cream,
			milk: product.milk,
		};
		keys[type].forEach(option => option.selected = false);
		item.selected = true;
		// console.log('当前产品配置:',product)
		currentProduct = product
		//	console.log('当前产品配置:', currentProduct)
	};
	// 计数器
	const changeCount = ({
		value,
		name
	}) => {
		count.value = value
		console.log("当前数量count:", count.value)
		product.count = count.value
		// total.value = e.value
	}
	//  点击购物车 或者 收藏按钮
	const onClick = async ({
		index,
		content
	}) => {
		if (index === 0) {
			// 前往购物车页面
			uni.switchTab({
				url: '/pages/cart/cart'
			})
		}
		// 收藏 toggle
		else if (index === 1) {
			// 已经收藏，取消收藏
			if (isFavorite.value) {
				console.log("取消收藏")
				isFavorite.value = false
				options.value[1].icon = 'heart'
				const res = await removeCollect(product.pid, uni.getStorageSync('coffee_token'))
				console.log("取消收藏：", res)
				if (res.code === 900) {
					uni.showToast({
						icon: 'success',
						title: '取消收藏'
					})
				}
			}
			// 没有收藏，确认收藏
			else {
				//确认收藏
				console.log("确认收藏")
				isFavorite.value = true
				options.value[1].icon = 'heart-filled'
				const res = await addCollect(product.pid, uni.getStorageSync('coffee_token'))
				console.log("addCollect 响应:", res); // 确认 res.code === 800
				if (res.code === 800) {
					uni.showToast({
						icon: 'success',
						title: '收藏成功'
					})
				}
			}
			// 检查收藏状态
			// collectStatus()
		}
	}
	
	// 更新购物车数量
// 更新购物车数量
const updateTotal = async () => {
    try {
        const count = await getShopcartCount(uni.getStorageSync('coffee_token'))
        console.log("购物车数量API返回:", count); // 调试信息
        
        if (count && count.code === 4000) {
            // 确保 result 是有效数字，如果不是则默认为 0
            total.value = count.result && !isNaN(count.result) ? parseInt(count.result) : 0
            options.value[0].info = total.value
        } else {
            // API 返回错误码或无效数据时，设置默认值
            total.value = 0
            options.value[0].info = 0
            console.log("购物车数量API返回错误码或无效数据");
        }
    } catch (error) {
        // API 调用失败时，设置默认值
        console.error("获取购物车数量失败:", error)
        total.value = 0
        options.value[0].info = 0
    }
    console.log("options.value[0].info", options.value[0].info)
}
	
	
	
	
	const isPidExist = (arr, targetPid) => {
		if (!Array.isArray(arr)) return false;
		return arr.some(item => item.pid === targetPid);
	};
	//查询商品收藏状态
	const collectStatus = async () => {
		const status = await getCollectStatus(product.pid, uni.getStorageSync('coffee_token'))
		console.log("collectStatus:", status)
		// {
		//     "msg": "查询收藏商品成功",
		//     "code": 1000,
		//     "result": []
		// }
		if (status.code === 1000) {
			// 已经收藏
			if (isPidExist(status.result, product.pid)) {
				//console.log('当前产品已经收藏')
				// 当前商品已经收藏了
				isFavorite.value = true
				options.value[1].icon = 'heart-filled';
				// 没有收藏
			} else {
				//当前商品没有收藏
				//console.log('当前产品没有收藏')
				isFavorite.value = false
				options.value[1].icon = 'heart';
			}
		}
	}
	// 添加到购物车
	const addCart = async ({
		index,
		content
	}) => {
		// 添加到购物车
		if (index === 0) {
			// 创建当前选择的产品对象
			const selectedProduct = {
				pid: currentProduct.pid,
				name: currentProduct.name,
				enname: currentProduct.enname,
				price: currentProduct.price,
				desc: currentProduct.desc,
				large_img: currentProduct.large_img,
				small_img: currentProduct.small_img,
				cream: Array.isArray(currentProduct.cream) ? currentProduct.cream.find(item => item?.selected)
					?.value ?? '' : currentProduct.cream || '',
				milk: Array.isArray(currentProduct.milk) ? currentProduct.milk.find(item => item?.selected)
					?.value ?? '' : currentProduct.milk || '',
				sugar: Array.isArray(currentProduct.sugar) ? currentProduct.sugar.find(item => item?.selected)
					?.value ?? '' : currentProduct.sugar || '',
				tem: Array.isArray(currentProduct.tem) ? currentProduct.tem.find(item => item?.selected)
					?.value ?? '' : currentProduct.tem || '',
				count: currentProduct.count // 当前选择的数量
			};
		
			// 已经登录
			if (uni.getStorageSync('coffee_token')) {
				const res = await addShopcart(selectedProduct.pid, selectedProduct.count, rules(selectedProduct),
					uni.getStorageSync('coffee_token'))
				if (res.code === 3000) {
					// 发送全局事件通知购物车刷新
					//uni.$emit('cartUpdated')
					if (res.status === 1) {
						// 添加产品 
						//	sid.value = res.sid  // sid: 购物袋的唯一标识
						console.log("新添加到购物车成功：", res)
						console.log("购物车sid：", res.sid)
						// 
						// 更新购物车数量
						await updateTotal()
						
						// {
						//     "msg": "加入购物车成功",
						//     "code": 3000,
						//     "status": 1,
						//     "sid": "_s1754100114536"
						// }
					} else if (res.status === 0) {
						// 修改产品数量
						console.log("增补产品数量成：", res)
						console.log("购物车sid：", res.sid)
						// {
						//     "msg": "加入购物车成功",
						//     "code": 3000,
						//     "status": 0,
						//     "sid": "_s1754100114536"
						// }
					}
					// options.value[0].info++
					uni.showToast({
						title: res.msg,
						icon: 'success'
					})
				}
			
			} else {
				uni.showToast({
					title: '请先登录',
					icon: 'error'
				})
			}
		}
	};
	// 返回上一页
	const goBack = () => {
		const pages = getCurrentPages();
		if (pages.length > 1) uni.navigateBack();
			else  uni.switchTab({ url: '/pages/index/index' });
	};
	// 商品规格
	const rules = (product) => {
		const parts = [];
		// 收集所有非空选项
		if (product.tem && product.tem !== '') parts.push(product.tem);
		if (product.sugar && product.sugar !== '') parts.push(product.sugar);
		if (product.cream && product.cream !== '') parts.push(product.cream);
		if (product.milk && product.milk !== '') parts.push(product.milk);
		// 用 "/" 连接所有选项
		return parts.join('/');
	}
	// 工具函数：将字符串或数组转换为对象数组
	const formatOptions = (data) => {
		let arr = [];
		if (typeof data === 'string') {
			arr = data.split('/').filter(item => item.trim() !== '');
		} else if (Array.isArray(data)) {
			arr = data;
		} else {
			return [];
		}
		return arr.map((item, index) => ({
			value: item,
			selected: index === 0,
		}));
	};
</script>
<style scoped>
	.container {
		padding: 0 20rpx 150rpx 20rpx;
	}

	.header {
		position: relative;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100rpx;
		border-bottom: 1rpx solid #eee;
	}

	.back-icon {
		position: absolute;
		left: 0;
		top: 50%;
		transform: translateY(-50%);
		display: flex;
		align-items: center;
		font-size: 28rpx;
	}

	.title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.product-image {
		width: 100%;
		height: 300rpx;
		border-radius: 20rpx;
		margin-top: 20rpx;
	}

	.product-info {
		padding: 20rpx;
	}

	.product-name {
		font-size: 32rpx;
		margin-bottom: 10rpx;
	}

	.product-english {
		font-size: 24rpx;
		color: #999;
		margin-bottom: 20rpx;
	}

	.product-price {
		float: right;
		color: red;
		font-weight: bold;
		font-size: 28rpx;
	}

	.option-group {
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: flex-start;
		margin-top: 30rpx;
		padding: 20rpx;
	}

	.option-label {
		font-size: 28rpx;
		margin-right: 20rpx;
		flex-shrink: 0;
		width: 120rpx;
	}

	.option-buttons {
		display: flex;
		gap: 20rpx;
	}

	.option-btn {
		background: #e8e8e8;
		border: 1rpx solid #ddd;
		padding: 10rpx 20rpx;
		border-radius: 40rpx;
		font-size: 24rpx;
		color: #444444;
	}

	.option-btn.active {
		background: #232773;
		color: white;
	}

	.quantity-control {
		margin-top: 30rpx;
		padding: 20rpx;
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
	}

	.minus {
		width: 22px;
		height: 22px;
		border-width: 1px;
		border-color: #E6E6E6;
		border-style: solid;
		border-top-left-radius: 100px;
		border-top-right-radius: 100px;
		border-bottom-left-radius: 100px;
		border-bottom-right-radius: 100px;
		/* #ifndef APP-NVUE */
		display: flex;
		/* #endif */
		justify-content: center;
		align-items: center;
	}

	.minus.disabled {
		opacity: 0.5;
	}

	.input {
		padding: 0 10px;
		text-align: center;
	}

	.plus {
		width: 22px;
		height: 22px;
		background-color: #FF0000;
		border-radius: 50%;
		display: flex;
		justify-content: center;
		align-items: center;
	}

	.description {
		margin-top: 30rpx;
		padding: 20rpx;
	}

	.desc-title {
		font-size: 28rpx;
		margin-bottom: 15rpx;
	}

	.desc-content {
		font-size: 24rpx;
		color: #666;
		line-height: 1.6;
	}

	.action-bar {
		display: flex;
		background: white;
		border-top: 1rpx solid #eee;
		padding: 20rpx 0;
		margin-top: 100rpx;
		position: fixed;
		left: 0;
		right: 0;
		/* #ifdef H5 */
		left: var(--window-left);
		right: var(--window-right);
		/* #endif */
		bottom: 0;
		z-index: 999;
	}
</style>